package com.jbwz.web.security.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.jbwz.web.common.base.BaseController;
import com.jbwz.web.common.res.ResponseJson;
import com.jbwz.web.common.session.SecurityUserHolder;
import com.jbwz.web.security.entity.RoleResource;
import com.jbwz.web.security.entity.vo.MenuTreeVO;
import com.jbwz.web.security.entity.vo.RoleResourceVO;
import com.jbwz.web.security.service.RoleResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色资源关联 前端控制器
 *
 * @author yyh
 * @since 2021-07-18 22:02:17
 */
@RestController
@RequestMapping("/role-resource")
public class RoleResourceController extends BaseController {

    @Autowired
    RoleResourceService roleResourceService;

    /**
     * 获取角色已授权的菜单id
     */
    @GetMapping("/list-rid/{roleId}")
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    public ResponseJson pageList(@PathVariable("roleId") Long roleId) {
        Set<Long> result = roleResourceService.listByRoleId(roleId);
        return success(result);
    }

    /**
     * 根据当前登录的角色获取此角色能授权的资源
     */
    @GetMapping("/list-mt-crid")
    public ResponseJson ListRVoByCRid() {
        List<Long> currentRoleIds = SecurityUserHolder.getCurrentRoleIds();
        MenuTreeVO result = roleResourceService.listByRVoByRoleIds(currentRoleIds);
        return success(result);
    }

    @PostMapping("/save")
    public ResponseJson save(@RequestBody RoleResourceVO e) {
        Set<RoleResource> list = e.getResourceIds().stream().map(v -> {
            RoleResource roleResource = new RoleResource();
            roleResource.setResourceId(v);
            roleResource.setRoleId(e.getRoleId());
            return roleResource;
        }).collect(Collectors.toSet());
        roleResourceService.removeByRoleId(e.getRoleId());
        if (!CollectionUtils.isEmpty(list)) {
            roleResourceService.saveOrUpdateBatch(list);
        }
        return success();
    }

}
